<template>
	<div class="upsert_container">
		<el-card class="box-card">
			<h3>商品（Spu）介绍</h3>
			<el-form :model='upsertForm' ref="upsertForm" :rules='rules' label-position="right" label-width="150px">
				<el-form-item label="商品名称" prop="title">
					<el-input  v-model="upsertForm.title"  style="width: 1000px !important;"></el-input>
				</el-form-item>
				<el-form-item label="原始价格" prop="originalPriceRaw">
					<el-input  v-model="upsertForm.originalPriceRaw"  placeholder="0.0" style="width: 1000px !important;">
						<template slot="append">元</template>
					</el-input>
				</el-form-item>
				<el-form-item label="当前价格" prop="priceRaw">
					<el-input v-model="upsertForm.priceRaw" style="width: 1000px !important;">
						<template slot="append">元</template>
					</el-input>
				</el-form-item>
				<el-form-item label="VIP价格" prop="vipPriceRaw">
					<el-input v-model="upsertForm.vipPriceRaw"  style="width: 1000px !important;">
						<template slot="append">元</template>
					</el-input>
				</el-form-item>
				<el-form-item label="剩余库存" prop="stock">
					<el-input v-model="upsertForm.stock" :disabled="true"  placeholder="0" style="width: 1000px !important;"></el-input>
				</el-form-item>
				<el-form-item label="运费模板" prop="freightTemplate">
					<el-select  v-model="upsertForm.freightTemplateId" placeholder="选择商品运费模板">
						<el-option v-for="(item, index) in freightList" :key="index"
							:label="item.freightTemplateDO.templateName" :value="item.freightTemplateDO.id" /></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="是否在售" prop="status">
					<el-radio-group  v-model="upsertForm.status">
						<el-radio :label="1">在售</el-radio>
						<el-radio :label="2">下架</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="商品图片">
					<el-upload  style="width: 1000px !important;" :action="uploadPath" :file-list="imgsFileList" :on-success="handleAvatarSuccess"
						:before-upload="beforeAvatarUpload" :on-remove="handleRemove" multiple  list-type="picture-card">
						<i class="el-icon-plus"></i>
					</el-upload>
				</el-form-item>
				<el-form-item label="商品单位" prop="unit">
					<el-input v-model="upsertForm.unit" placeholder="件 / 个 / 盒" style="width: 1000px !important;"></el-input>
				</el-form-item>
				<el-form-item label="所属类目" prop="category">
					<el-cascader :options="categoryList" v-model="categoryIds" expand-trigger="hover" @change="handelCategory"/>
				</el-form-item>
				<el-form-item label="商品简介" prop="description">
					<el-input v-model="upsertForm.description" style="width: 1000px !important;"></el-input>
				</el-form-item>
				<el-form-item label="商品详细介绍" prop="detail">
					<editor v-model="upsertForm.detail"   style="width: 1000px !important;" api-key="2qxod96jqhfnpi8rmprxm6m6gzc2ljxdjwo022457dqbz2vm" :init="editorInit"/>
				</el-form-item>
			</el-form>
		</el-card>
		<el-card class="box-card">
			<h3>商品类型（sku）</h3>
			<el-button :plain="true" type="primary"
				style="width: 80px !important;height:40px;font-size: 14px;margin: 20px 0;" @click='createSku()'>添加</el-button>
			<el-table :data="skuList">
				<el-table-column align="center" label="Sku条形码" prop="barCode" />
				<el-table-column align="center" label="类型名" prop="title"/>
				<el-table-column align="center" label="原价" prop="originalPriceRaw" />
				<el-table-column align="center" label="现价" prop="priceRaw"/>
				<el-table-column align="center" label="VIP价" prop="vipPriceRaw" />
				<el-table-column align="center" label="库存" prop="stock"/>
				<el-table-column align="center" label="操作" width="100" class-name="small-padding fixed-width">
					<template slot-scope="scope">
						<el-button type="danger" size="mini" @click='delSkuList(scope.row)'>删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-card>
		<el-dialog :visible.sync="skuDialogVisible" title="添加商品类型(sku)">
			<el-form  :model="skuForm"  ref="skuForm" status-icon label-position="left"
					label-width="100px" style="width: 400px; margin-left:50px;" :rules='skuRules'>
				<el-form-item label="类型条形码" prop="barCode">
					<el-input v-model="skuForm.barCode"></el-input>
				</el-form-item>
				<el-form-item label="类型名称" prop="title">
					<el-input v-model="skuForm.title"></el-input>
				</el-form-item>
				<el-form-item label="图片(可空)" prop="title">
					<el-upload :action="uploadPath" :show-file-list="false" :on-success="handleSkuImgSuccess"
						class="avatar-uploader">
						<img v-if="skuForm.img" :src="skuForm.img" class="avatar" />
						<i v-else class="el-icon-plus avatar-uploader-icon" />
					</el-upload>
				</el-form-item>
				<el-form-item label="原始价格" prop="originalPriceRaw">
					<el-input v-model="skuForm.originalPriceRaw" placeholder="0.00">
						<template slot="append">元</template>
					</el-input>
				</el-form-item>
				<el-form-item label="当前价格" prop="priceRaw">
					<el-input v-model="skuForm.priceRaw" placeholder="0.00">
						<template slot="append">元</template>
					</el-input>
				</el-form-item>
				<el-form-item label="VIP价格" prop="vipPriceRaw">
					<el-input v-model="skuForm.vipPriceRaw" placeholder="0.00">
						<template slot="append">元</template>
					</el-input>
				</el-form-item>
				<el-form-item label="库存" prop="stock">
					<el-input v-model="skuForm.stock" />
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="closeSkuDialog()">取消</el-button>
				<el-button type="primary" @click="confirmSkuFrom('skuForm')">确定</el-button>
			</div>
		</el-dialog>
		<el-card class="box-card">
			<h3>商品参数</h3>
			<el-button :plain="true" type="primary"
				style="width: 80px !important;height:40px;font-size: 14px;margin: 20px 0;" @click='createAttributes()'>添加</el-button>
			<el-table :data="attributes">
				<el-table-column align="center" label="商品参数名称" prop="attribute"/>
				<el-table-column align="center" label="商品参数值"prop="value" />
				<el-table-column align="center" label="操作">
					<template slot-scope="scope">
						<el-button type="danger" size="mini" @click='delAttributes(scope.row)'>删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-card>
		<el-dialog :visible.sync="attributeVisiable" title="设置商品参数" >
			<el-form ref="attributeForm" :model="attributeForm":data="attributes" status-icon
				label-position="left" label-width="120px" style="width: 420px; margin-left:50px;" :rules='rules'>
				<el-form-item label="商品参数名称" prop="attribute">
					<el-input v-model="attributeForm.attribute" />
				</el-form-item>
				<el-form-item label="商品参数值" prop="value">
					<el-input v-model="attributeForm.value" />
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="attributeVisiable = false">取消</el-button>
				<el-button type="primary" @click="confirmAttribute('attributeForm')">确定</el-button>
			</div>
		</el-dialog>
		<div class="op-container">
			<el-button @click="handleCancel">取消</el-button>
			<el-button v-if="!upsertForm.id" type="primary" @click='createGood("upsertForm")'>保存商品</el-button>
			<el-button v-if="upsertForm.id" type="primary" @click='updateGood("upsertForm")'>更新商品</el-button>
		</div>
	</div>
</template>

<script>
	import {
		uploadPath,
		getFreightList,
		getCategory,
		getGoodsDetail,
		editGoods,
		createGoods,
		tinymceImg
	} from "../api.js";
	import Editor from '@tinymce/tinymce-vue'
	export default {
		components: { editor: Editor },
		data() {
			return {
				editorInit: {
				  language: 'zh_CN',
				  convert_urls: false,
				  plugins: [
				    'advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount'
				  ],
				  toolbar: [
				    'searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample',
				    'hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen'
				  ],
				 images_upload_handler: function(blobInfo, success, failure) {
				 	       let formdata = new FormData()
				 	       // append 方法中的第一个参数就是 我们要上传文件 在后台接收的文件名
				 	       // 这个值要根据后台来定义
				 	       // 第二个参数是我们上传的文件
				 	       formdata.append('file', blobInfo.blob())
				 	       // axios 定义上传方法
				 	       tinymceImg(formdata).then(res => {
							   console.log(res.errno)
				 	         if (res.data.errno != 200) {
				 	           // 上传失败执行此方法，将失败信息填入参数中
				 	           failure(res.msg);
				 	           return
				 	         }
				 	         // 上传成功之后，将对应完整的图片路径拼接在success的参数中
				 	         success(res.data.url);
				 	       })
				 }
				},
				upsertForm: {
				imgList: [],
				priceRaw: 0
				},
				skuDialogVisible:false,
				attributeVisiable:false,
				uploadPath,
				tinymceImg,
				imgsFileList: [],
				content: "",
				rules: {
					title:[{
						required: true,
						message: "商品名称不能为空",
						trigger: "blur"
					}],
					originalPriceRaw:[{
						required: true,
						message: "原始价格不能为空",
						trigger: "blur"
					}],
					priceRaw:[{
						required: true,
						message: "当前价格不能为空",
						trigger: "blur"
					}],
					vipPriceRaw:[{
						required: true,
						message: "商品ViP价格不能为空",
						trigger: "blur"
					}],
					status: [{
						required: true,
						message: "请选择商品状态",
						trigger: "blur"
					}],
					unit:[{
						required: true,
						message: "物件单位不能为空",
						trigger: "blur"
					}],
					detail: [{
						required: true,
						message: "请填写商品详情",
						trigger: "blur"
					}],
					attribute: [{
						required: true,
						message: "属性名称不能为空",
						trigger: "blur"
					}],
					value: [{
						required: true,
						message: "属性值不能为空",
						trigger: "blur"
					}],
					barCode: [{
						required: true,
						message: "类型条码不能为空",
						trigger: "blur"
					}],	
				},
				skuRules:{
					title: [{
						required: true,
						message: "类型名称不能为空",
						trigger: "blur"
					}],
					priceRaw: [{
						required: true,
						message: "类型现价不能为空",
						trigger: "blur"
					}],
					originalPriceRaw: [{
						required: true,
						message: "类型原价不能为空",
						trigger: "blur"
					}],
					vipPriceRaw: [{
						required: true,
						message: "类型VIP价格不能为空",
						trigger: "blur"
					}],
					stock: [{
						required: true,
						message: "类型库存不能为空",
						trigger: "blur"
					}]
				},
				categoryIds: undefined,
				categoryList: [],
				freightList:[],
				skuList:[],
				attributes: [],
				skuForm:{
					img: undefined
				},
				attributeForm:{
					attribute: "",
					value: ""
				},
			}
		},
		methods: {
			// 获取数据
			getData() {
				getCategory().then((res) => {
					this.categoryList = this.getTreeData(res.data.data)
				});
				getFreightList().then((res) => {
					this.freightList = res.data.data;
				})
				if(this.$route.query.id){
					getGoodsDetail(this.$route.query.id).then((res)=>{
						this.attributes= res.data.data.attributeList;
						this.categoryIds = res.data.data.categoryIds.reverse();
						this.skuList = res.data.data.skuList;
						res.data.data.priceRaw = res.data.data.price / 100;
						res.data.data.originalPriceRaw = res.data.data.originalPrice / 100;
						res.data.data.vipPriceRaw = res.data.data.vipPrice / 100;
						this.upsertForm = Object.assign({}, res.data.data);
						this.imgsFileList = [];
						for (var i = 0; i < this.upsertForm.imgList.length; i++) {
							this.imgsFileList.push({url: this.upsertForm.imgList[i]});
						}
						if (this.upsertForm.skuList) {
							for (var j = 0; j < this.upsertForm.skuList.length; j++) {
								this.skuList[j].priceRaw = this.skuList[j].price / 100;
								this.skuList[j].originalPriceRaw = this.skuList[j].originalPrice / 100;
								this.skuList[j].vipPriceRaw = this.skuList[j].vipPrice / 100;
							}
						}
					})
				}
			},
			// 递归
			getTreeData(data) {
				for (var i = 0; i < data.length; i++) {
					if ('children' in data[i]) {
						if (data[i].children.length < 1) {
							// children若为空数组，则将children设为undefined
							data[i].children = undefined;
						} else {
							// children若不为空数组，则继续 递归调用 本方法
							this.getTreeData(data[i].children);
						}
					}
				}
				return data;
			},
			handleAvatarSuccess(response) {
					this.upsertForm.imgList.push(response.url);
					this.upsertForm.img = this.upsertForm.imgList[0];
			},
			beforeAvatarUpload(file) {
				const isJPG = file.type === "image/jpeg";
				const isLt2M = file.size / 1024 / 1024 < 2;
                 if(this.upsertForm.imgList.length === 5){
                 	this.$message.error("上传文件个数超出限制!最多上传5张图片!");
                 	return false;
                 }  
				if (!isJPG) {
					this.$message.error("上传头像图片只能是 JPG 格式!");
				}
				if (!isLt2M) {
					this.$message.error("上传头像图片大小不能超过 2MB!");
				}
				return isJPG && isLt2M;
			},
			// 删除图片
			handleRemove(file) {
				// console.log(file)
				for (var i = 0; i < this.upsertForm.imgList.length; i++) {
					var url;
					if (file.response === undefined) {
						url = file.url;
					} else {
						url = file.response.url;
					}
					if (this.upsertForm.imgList[i] === url) {
						this.upsertForm.imgList.splice(i, 1);
					}
				}
				// if (this.upsertForm.imgList.length > 0) {
				// 	this.upsertForm.img = this.upsertForm.imgList[0];
				// }
			},
			handelCategory(e){
				// console.log(e)
				this.upsertForm.categoryId = e[e.length - 1]
			},
			// 删除商品类型
			delSkuList(value){
				let index = this.skuList.indexOf(value);
				this.skuList.splice(index, 1);
			},
			createSku(){
				this.skuDialogVisible = true;
				this.skuForm = {}
				// 清空表单验证
				if (this.$refs.skuForm != undefined) {
					this.$refs.skuForm.resetFields(); //form表单的dom渲染完在执行this.$refs.couponForm.resetFields()，去除验证
				}
			},
			handleSkuImgSuccess(e) {
				// console.log(e)
				this.skuForm.img = e.url;
				this.skuDialogVisible = false;
				this.skuDialogVisible = true;
			},
			// 删除商品参数
			delAttributes(value){
				let index = this.attributes.indexOf(value);
				this.attributes.splice(index, 1);
			},
			// 确认商品类型
			confirmSkuFrom(formName){
				this.$refs[formName].validate(valid => {
					if (valid) {
						this.skuForm.price = this.skuForm.priceRaw * 100;
						this.skuForm.originalPrice = this.skuForm.originalPriceRaw * 100;
						this.skuForm.vipPrice = this.skuForm.vipPriceRaw * 100;
						var data = Object.assign({}, this.skuForm);
						this.skuList.unshift(data);
						this.skuDialogVisible = false;
					}else{
						return false;
					}
					})
			},
			closeSkuDialog(){
				this.skuDialogVisible = false;
			},
			createAttributes(){
				this.attributeVisiable = true;
				this.attributeForm = {}
				// 清空表单验证
				if (this.$refs.attributeForm != undefined) {
					this.$refs.attributeForm.resetFields(); //form表单的dom渲染完在执行this.$refs.couponForm.resetFields()，去除验证
				}
			},
			// 确认商品参数
			confirmAttribute(formName){
				this.$refs[formName].validate(valid => {
					if (valid) {
						this.attributes.unshift(this.attributeForm);
						this.attributeVisiable = false;
					}else{
						return false
					}
				})
			},
			// 编辑商品
			updateGood(formName){
				this.$refs[formName].validate(valid => {
					if (valid) {
						if (this.skuList.length === 0) {
							this.$message.error("请添加类型")
						}else if (this.upsertForm.imgList.length === 0) {
							this.$message.error("请上传至少一张图片");
						}else if (this.categoryId === undefined) {
							this.$message.error("请选择类目");
						}else{
							this.upsertForm.price = this.upsertForm.priceRaw * 100
							this.upsertForm.originalPrice = this.upsertForm.originalPriceRaw * 100
							this.upsertForm.vipPrice = this.upsertForm.vipPriceRaw * 100
							let form = {
								...this.upsertForm,
								attributeList:this.attributeList,
								skuList:this.skuList
							}
							editGoods(form).then((res)=>{
								console.log(res)
							}).then(() => {
									this.$message.success("编辑成功");
									this.$router.push({
										path: "/goods/goodslist"
									});
								})
						}
					}else{
					  this.$message.error("请完善表单信息")
					}
				})
			},
			// 添加商品
			createGood(formName){
				this.$refs[formName].validate(valid => {
					if (valid) {
						console.log(this.categoryIds)
						if (this.upsertForm.freightTemplateId === undefined) {
							this.$message.error("请添加运费模板");
						} else if (this.skuList.length === 0) {
							this.$message.error("请添加商品类型");
						} else if (this.categoryIds === undefined || this.categoryIds.length < 3) {
							this.$message.error("请选择类目");
						}else if (this.upsertForm.imgList.length === 0) {
							this.$message.error("请上传至少一张图片");
						}else {
							this.upsertForm.price = this.upsertForm.priceRaw * 100
							this.upsertForm.originalPrice = this.upsertForm.originalPriceRaw * 100
							this.upsertForm.vipPrice = this.upsertForm.vipPriceRaw * 100
							let form = {
								...this.upsertForm,
								attributeList: this.attributes,
								skuList: this.skuList
							};
							createGoods(form).then((res) => {
									console.log(res)
									if(res.data.errno === 200){
										this.$message.success("添加成功");
										this.$router.push({path: "/goods/goodslist"});
									}else{
										this.$message.error(res.data.errmsg)
									}
								})
						}
					} else {
						this.$message.error("请完善以上表单息");
					}
				});
			},
			// 取消
			handleCancel(){
					this.$router.push({
						path: "/goods/goodslist"
					});
			},
			
		},
		created() {
			this.getData();
			// console.log(this.$route.query.id)
		}
	}
</script>

<style>
	.upsert_container {
		width: 100%;
		height: 660px;
		overflow-x: auto;
		overflow-y: auto;
		padding: 20px;
	}

	.box-card {
		margin-bottom: 10px;
	}

	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		display: inline-block;
	}

	.avatar-uploader .el-upload:hover {
		border-color: #20a0ff;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 120px;
		height: 120px;
		line-height: 120px;
		text-align: center;
	}

	.avatar {
		width: 145px;
		height: 145px;
		display: inline-block;
	}
</style>
